package com.xcn.siteinfo;


import java.io.*;
import java.net.*;
import java.util.*;

import org.jsoup.*;
import org.jsoup.helper.*;
import org.jsoup.nodes.*;
import org.jsoup.select.*;

import au.com.bytecode.opencsv.*;

public class Test
{
	public static final String SEPARATOR = ";";
	
	public String[] getData ( int id )
	{
		String[] result = new String[7];
		int idx = 0;
		try
		{
			Connection con = HttpConnection.connect ( new URL ( "http://www.laotradeportal.gov.la/index.php?r=tradeInfo/view&id=" + id ) );
			con.header ( "Cookie", "__utma=54512821.1873445506.1369386254.1369399992.1369409833.3; __utmz=54512821.1369386254.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmc=54512821; __utmb=54512821.14.10.1369409833; PHPSESSID=462c852feea2c31a1cc3845e766c7c26" );
			Document doc = con.get ( );

			Element content = doc.getElementById ( "content" );
			if ( content != null )
			{
				for ( int i=0 ; i < content.childNodeSize ( ) ; i++ )
				{
					Node node = content.childNode ( i );
					if ( node.nodeName ( ).equals ( "#text" ) && node.toString ( ).trim( ).length ( ) > 0 )
					{
						result[idx++] = node.toString ( ).trim ( ).replaceAll ( "&nbsp;", "" );
					}
				}
			}
			Elements odds = doc.getElementsByClass ( "odd" );
			Element odd = odds.get ( 0 );
			result[idx++] = odd.childNode ( 0 ).childNode ( 0 ).toString ( ).replaceAll ( "&nbsp;", "" );
			result[idx++] = odd.childNode ( 2 ).childNode ( 0 ).toString ( ).replaceAll ( "&nbsp;", "" );
			result[idx++] = odd.childNode ( 3 ).childNode ( 0 ).toString ( ).replaceAll ( "&nbsp;", "" );
		}
		catch ( SocketTimeoutException e )
		{
			e.printStackTrace ( );
			getData ( id );
		}
		catch ( Exception e )
		{
			e.printStackTrace ( );
		}
		return result;
	}
	
	public static void main ( String[] args )
	{
		int startId = 6527;
		int endId = 6535;

		CSVWriter csvWriter = null;
		List<String[]> result = new ArrayList <String[]> ( );
		try
		{
			Test ts = new Test ( );
			for ( int i = startId ; i <= endId ; i++ )
			{
				result.add ( ts.getData ( i ) );
			}
			System.out.println ( result.size ( ) );

			csvWriter = new CSVWriter ( new FileWriter ( new File ( "c:/out.csv" ) ) );
			csvWriter.writeAll ( result );
		}
		catch ( Exception e )
		{
			e.printStackTrace ( );
		}
		finally
		{
			try { if ( csvWriter != null )csvWriter.close ( ); } catch ( Exception e2 ) { e2.printStackTrace ( ); } 
		}
	}
}
